package cn.fl.mcr.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.lionbridgecapital.loan.model.base.Pager;
import cn.lionbridgecapital.loan.model.condition.McrCityOpenQC;
import cn.lionbridgecapital.loan.model.condition.McrLoanChannelQC;
import cn.lionbridgecapital.loan.model.dto.McrLoanChannelDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.mcr.service.IMcrLoanChannelService;
import cn.fl.mcr.vo.McrLoanChannelVO;
import cn.fl.system.constant.SysLogConstant;

import com.alibaba.fastjson.JSONObject;

/**
 * @Description: 机构（借款通道） 控制层
 */
@Controller
@RequestMapping("/mcr/mcrLoanChannel")
public class McrLoanChannelController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(McrLoanChannelController.class);

	/**
	 * McrLoanChannel 服务层BEAN
	 */
	@Autowired
	private IMcrLoanChannelService mcrLoanChannelService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do")
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("mcr/mcrLoanChannel/mcrLoanChannelList");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到新增修改页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toAddPage", "加载例子新增页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("mcr/mcrLoanChannel/mcrLoanChannelAdd");
		view.addObject("id", id);
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toAddPage", "加载例子新增页面.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return view;
	}
	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do")
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response, McrLoanChannelQC qc) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		page.setCondition(qc);
		Pager pager = this.mcrLoanChannelService.searchListPage(page);
		if(pager.getResultList()!=null && pager.getResultList().size()>0){
			List<McrLoanChannelDTO> list = new ArrayList<McrLoanChannelDTO>();
			for (Object obj : pager.getResultList()) {
				McrLoanChannelDTO dto = (McrLoanChannelDTO) obj;
				dto.setRemainAmt(DecimalUtils.convertFenToYuan(dto.getRemainAmt()).longValue());
				list.add(dto);
			}
			pager.setResultList(list);
		}
		List<McrLoanChannelVO> list = (List<McrLoanChannelVO>) pager.getResultList();
		ListPageVO<McrLoanChannelVO> listPage = new ListPageVO<McrLoanChannelVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do")
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.mcrLoanChannelService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do")
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			McrLoanChannelVO vo = this.mcrLoanChannelService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			vo.setRemainAmt(DecimalUtils.convertFenToYuan(vo.getRemainAmt()).longValue());
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do")
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response, McrLoanChannelVO entity) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		try {
			entity.setRemainAmt(DecimalUtils.convertYuanToFen(entity.getRemainAmt().doubleValue()));
			McrLoanChannelQC qc = new McrLoanChannelQC();
			qc.setSort(entity.getSort());
			List<McrLoanChannelDTO> list = mcrLoanChannelService.searchList(qc);
			BaseLogUtils.info(logger, "modify", "新增小贷资方机构 DATA:" + JSONObject.toJSONString(list), CurrentThreadContext.getCurrentUserName());
			if(CollectionUtils.isNotEmpty(list)){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("排序不能重复!!!");
				return result;
			}
			Long id = this.mcrLoanChannelService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do")
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response, McrLoanChannelVO entity) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			entity.setId(Long.valueOf(id));
			if(StringUtils.isNotEmpty(entity.getRemainAmt())){
				entity.setRemainAmt(DecimalUtils.convertYuanToFen(entity.getRemainAmt().doubleValue()));
			}
			if(StringUtils.isNotEmpty(entity.getSort())){
				McrLoanChannelQC qc = new McrLoanChannelQC();
				qc.setSort(entity.getSort());
				List<McrLoanChannelDTO> list = mcrLoanChannelService.searchList(qc);
				BaseLogUtils.info(logger, "modify", "修改小贷资方机构 DATA:" + JSONObject.toJSONString(list), CurrentThreadContext.getCurrentUserName());
				if(CollectionUtils.isNotEmpty(list) && list.size() > 1){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("排序不能重复!!!");
					return result;
				}else if(CollectionUtils.isNotEmpty(list) && !list.get(0).getId().toString().equals(id)){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("排序不能重复!!");
					return result;
				}
			}
			boolean success = this.mcrLoanChannelService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
}

